package com.wb.mas.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.facebook.accountkit.AccountKitError;
import com.facebook.accountkit.AccountKitLoginResult;
import com.facebook.accountkit.ui.AccountKitActivity;
import com.facebook.accountkit.ui.AccountKitConfiguration;
import com.facebook.accountkit.ui.LoginType;
import com.gyf.immersionbar.ImmersionBar;
import com.wb.mas.BR;
import com.wb.mas.BuildConfig;
import com.wb.mas.R;
import com.wb.mas.app.AppViewModelFactory;
import com.wb.mas.databinding.ActLoginBinding;
import com.wb.mas.ui.main.MainActivity;

import java.util.HashMap;
import java.util.Map;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import me.goldze.mvvmhabit.base.BaseActivity;

public class LoginAc extends BaseActivity<ActLoginBinding, LoginViewModel> {


    protected void initStatusBar() {
        ImmersionBar.with(this)
                .navigationBarColor(R.color.transparent)
                .init();  //必须调用方可沉浸式
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.act_login;
    }

    @Override
    public int initVariableId() {
        return BR.loginViewModel;
    }

    //    @Override
//    public LoginViewModel initViewModel() {
//        return new LoginViewModel(AppApplication.getInstance(),new DemoRepository(Injection.provideDemoRepository().));
//    }
    @Override
    public LoginViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(LoginViewModel.class);
    }


    @Override
    public void initData() {
        super.initData();
        viewModel.uc.loginEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                phoneLogin();
            }
        });

        viewModel.uc.loginSucEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {

                Intent mainIntent = new Intent(LoginAc.this, MainActivity.class);
                LoginAc.this.startActivity(mainIntent);
            }
        });
    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.ui.showLoginUiEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                binding.rootContainer.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (BuildConfig.isDebug) {
            binding.tvReplaceLogin.setVisibility(View.VISIBLE);
        } else {
            binding.tvReplaceLogin.setVisibility(View.GONE);
        }
    }

    public static int APP_REQUEST_CODE = 99;

    public void phoneLogin() {

        String[]  whitelist=new String[]{"ID"};
        final Intent intent = new Intent(LoginAc.this, AccountKitActivity.class);
        AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder = new
                AccountKitConfiguration.AccountKitConfigurationBuilder(LoginType.PHONE,
                AccountKitActivity.ResponseType.CODE).setDefaultCountryCode("ID").setSMSWhitelist(whitelist);
//        AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder = new
//                AccountKitConfiguration.AccountKitConfigurationBuilder(LoginType.PHONE,
//                AccountKitActivity.ResponseType.CODE).setDefaultCountryCode("ID");
//
        // ... perform additional configuration ...
        intent.putExtra(AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
                configurationBuilder.build());
        // ... perform additional configuration ...
        intent.putExtra(
                AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
                configurationBuilder.build());
        startActivityForResult(intent, APP_REQUEST_CODE);
    }


    @Override
    protected void onActivityResult(
            final int requestCode,
            final int resultCode,
            final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == APP_REQUEST_CODE) { // confirm that this response matches your request
            AccountKitLoginResult loginResult = data.getParcelableExtra(AccountKitLoginResult.RESULT_KEY);
            String toastMessage;
            if (loginResult.getError() != null) {
                toastMessage = loginResult.getError().getErrorType().getMessage();
                showErrorActivity(loginResult.getError());
            } else if (loginResult.wasCancelled()) {
                toastMessage = "Login Cancelled";
            } else {
                if (loginResult.getAccessToken() != null) {
                    toastMessage = "Success:" + loginResult.getAccessToken().getToken();


                } else {
                    toastMessage = String.format(
                            "Success:%s...",
                            loginResult.getAuthorizationCode().substring(0, 10));
                }

                Map<String, Object> param = new HashMap<>();
                param.put("channel", BuildConfig.channel);
                param.put("authCode", loginResult.getAuthorizationCode());

                viewModel.login(param);

                // If you have an authorization code, retrieve it from
                // loginResult.getAuthorizationCode()
                // and pass it to your server and exchange it for an access token.

                // Success! Start your next activity...
//                goToMyLoggedInActivity();
            }

            // Surface the result to your user in an appropriate way.
//            ToastUtils.showShort(toastMessage);
        }
    }

    private void showErrorActivity(AccountKitError error) {

    }
}
